package project;

import java.util.*;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintWriter;


// 学生类，用于存储学生信息和他们的成绩
class Student {
    private String id; // 学生ID
    private String name; // 学生姓名
    private List<Course> courses = new ArrayList<>(); // 学生选修的课程列表，使用ArrayList实现

    // 构造函数，初始化学生信息
    public Student(String id, String name) {
        this.id = id;
        this.name = name;
    }

    // 添加课程到学生课程列表
    public void addCourse(Course course) {
        courses.add(course);
    }

    // 计算GPA
    public double calculateGPA() {
        double totalQualityPoints = 0; // 总质量点数
        int totalCredits = 0; // 总学分
        for (Course course : courses) {
            totalQualityPoints += course.getGradePoints() * course.getCredits(); // 计算总质量点数
            totalCredits += course.getCredits(); // 计算总学分
        }
        return totalCredits > 0 ? totalQualityPoints / totalCredits : 0.0; // 返回GPA值（三元运算符表达式）
    }

    // 获取学生ID
    public String getId() {
        return id;
    }

    // 获取学生姓名
    public String getName() {
        return name;
    }

    // 获取学生课程列表
    public List<Course> getCourses() {
        return courses;
    }

    // 将GPA转换为字母分制
    public String getGPALetterGrade() {
        double gpa = calculateGPA();
        if (gpa >= 4.0) return "A";
        else if (gpa >= 3.5) return "B+";
        else if (gpa >= 3.0) return "B";
        else if (gpa >= 2.5) return "C+";
        else if (gpa >= 2.0) return "C";
        else if (gpa >= 1.5) return "D+";
        else if (gpa >= 1.0) return "D";
        else return "F";
    }
}

// 课程类，用于存储课程信息和成绩转换为GPA点数
class Course {
    private String id; // 课程ID
    private String name; // 课程名称
    private double credits; // 课程学分
    private double grade; // 学生成绩

    // 构造函数，初始化课程信息
    public Course(String id, String name, double credits, double grade) {
        this.id = id;
        this.name = name;
        this.credits = credits;
        this.grade = grade;
    }

    // 将百分制成绩转换为GPA点数
    public double getGradePoints() {
        if (grade >= 90) return 4.0;
        else if (grade >= 80) return 3.0;
        else if (grade >= 70) return 2.0;
        else if (grade >= 60) return 1.0;
        else return 0.0;
    }

    // 获取课程ID
    public String getId() {
        return id;
    }

    // 获取课程名称
    public String getName() {
        return name;
    }

    // 获取课程学分
    public double getCredits() {
        return credits;
    }

    // 获取学生成绩
    public double getGrade() {
        return grade;
    }
}

// 可查询某个学生的GPA
public class GPACalcultaor {
    public static void main(String[] args) {
        Map<String, Student> students = new HashMap<>();
        Scanner scanner = new Scanner(System.in);

        // 读取初始文件
        String initialFilePath = "C:\\Users\\yueli\\Desktop\\java\\Student.txt";
        importStudentInfo(initialFilePath, students);

        // 实时导入学生信息
        while (true) {
            System.out.println("Do you want to import more students or add a new student? (y/n)");
            String input = scanner.nextLine();
            if (input.equalsIgnoreCase("y")) {
                System.out.println("Enter the path of the new student information file or type 'new' to add a student manually:");
                String additionalFilePath = scanner.nextLine();
                if ("new".equalsIgnoreCase(additionalFilePath)) {
                    System.out.print("Enter Student ID: ");
                    String studentId = scanner.nextLine();

                    System.out.print("Enter Student Name: ");
                    String studentName = scanner.nextLine();

                    Student newStudent = new Student(studentId, studentName);
                    students.put(studentId, newStudent);

                    while (true) {
                        System.out.print("Do you want to add a course for this student? (y/n): ");
                        String courseInput = scanner.nextLine();
                        if (courseInput.equalsIgnoreCase("y")) {
                            System.out.print("Enter Course ID: ");
                            String courseId = scanner.nextLine();

                            System.out.print("Enter Course Name: ");
                            String courseName = scanner.nextLine();

                            System.out.print("Enter Credits: ");
                            double credits = Double.parseDouble(scanner.nextLine());

                            System.out.print("Enter Grade: ");
                            double grade = Double.parseDouble(scanner.nextLine());
                            Course newCourse = new Course(courseId, courseName, credits, grade);
                            newStudent.addCourse(newCourse);
                        } else {
                            break;
                        }
                    }
                } else {
                    importStudentInfo(additionalFilePath, students);
                }
            } else {
                break;
            }
        }

        // 导出学生记录
        try {
            exportStudentRecords(students, "C:\\Users\\yueli\\Desktop\\java\\GPAout.txt");
        } catch (IOException e) {
            System.err.println("Error exporting student records: " + e.getMessage());
        }
        queryStudentGrades(students, scanner);
    }


    // 解析课程信息的方法
    private static Course parseCourse(String[] parts) {
        if (parts.length < 4) {
            throw new IllegalArgumentException("Invalid course data format.");
        }
        String courseId = parts[0].substring("Course ID:".length()).trim();
        String courseName = parts[1].substring("Course Name:".length()).trim();
        double credits = Double.parseDouble(parts[2].substring("Credits:".length()).trim());
        double grade = Double.parseDouble(parts[3].substring("Grade:".length()).trim());
        return new Course(courseId, courseName, credits, grade);
    }

    // 导出学生记录到TXT文件的方法
    private static void exportStudentRecords(Map<String, Student> students, String filePath) throws IOException {
        try (PrintWriter writer = new PrintWriter(filePath)) {
            for (Student student : students.values()) {
                writer.println("Student: " + student.getName() + " (" + student.getId() + ")");
                writer.println("GPA: " + student.calculateGPA() + " (" + student.getGPALetterGrade() + ")");
                for (Course course : student.getCourses()) {
                    writer.println(course.getName() + ": " + course.getGrade());
                }
                writer.println();
            }
        }
    }

    // 根据学生ID查询学生成绩
    private static void queryStudentGrades(Map<String, Student> students,Scanner scanner) {
        System.out.print("Enter Student ID to query: ");
        String studentId = scanner.nextLine(); // 从控制台获取学生ID

        Student student = students.get(studentId);
        if (student != null) {
            System.out.println("Student: " + student.getName() + " (" + student.getId() + ")");
            System.out.println("GPA: " + student.calculateGPA() + " (" + student.getGPALetterGrade() + ")");
            for (Course course : student.getCourses()) {
                System.out.println("Course: " + course.getName() + ", Grade: " + course.getGrade() + ", GPA: " + course.getGradePoints());
            }
        } else {
            System.out.println("Student with ID " + studentId + " not found.");
        }
    }

    // 导入学生信息的方法
    private static void importStudentInfo(String filePath, Map<String, Student> students) {
        try (Scanner fileScanner = new Scanner(new File(filePath))) {
            Student currentStudent = null;

            while (fileScanner.hasNextLine()) {
                String line = fileScanner.nextLine().trim();
                if (line.startsWith("Student ID:")) {
                    String studentId = line.substring("Student ID:".length()).trim();
                    line = fileScanner.nextLine().trim();
                    String studentName = line.substring("Student Name:".length()).trim();
                    currentStudent = new Student(studentId, studentName);
                    students.put(studentId, currentStudent);
                } else if (line.startsWith("Course ID:") && currentStudent != null) {
                    String[] parts = line.split(", ");
                    if (parts.length >= 4) {
                        try {
                            Course course = parseCourse(parts);
                            currentStudent.addCourse(course);
                        } catch (NumberFormatException e) {
                            System.err.println("Invalid number format: " + e.getMessage());
                        }
                    }
                }
            }
        } catch (FileNotFoundException e) {
            System.err.println("File not found: " + e.getMessage());
        }
    }
}
